<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" @submit.native.prevent>
      <el-form-item label="应用名称" prop="appName">
        <el-input v-model="queryParams.appName" placeholder="请输入应用名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd('')">新增应用</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="menuList" :default-expand-all="expand" row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">

      <el-table-column prop="appName" label="应用名称" :show-overflow-tooltip="true" width="160" />
      <el-table-column prop="appCode" label="应用编码" :show-overflow-tooltip="true" width="160" />
      <el-table-column prop="appsTypeName" label="类型" :show-overflow-tooltip="true" width="160" />
      <el-table-column prop="appSort" label="排序" width="160"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="160"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)">新增</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-row>
          <el-col :span="18">
            <el-form-item v-show="isAdd && !newApp" label="上级应用/分类" prop="pidName" label-width="100px">
              <el-input v-model="form.pidName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item v-show="!isAdd" label="上级应用/分类">
              <treeselect v-model="form.parentId" :options="menuOptions" :normalizer="normalizer" :show-count="true"
                placeholder="选择上级应用/分类" />
            </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item :label="newApp?'应用名称':'分类名称'" prop="appName" label-width="100px">
              <el-input v-model="form.appName" @change="getAppCode" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item v-show="newApp || editNowIsApp" label="应用编码" prop="appCode" label-width="100px">
              <el-input v-model="form.appCode" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item label="排序" prop="appSort" label-width="100px">
              <el-input type="number" v-model="form.appSort" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item label="注释" label-width="100px">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入注释" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
  import {
    listActApps,
    findById,
    genAppCode,
    addNewApp,
    updateApp,
    delActApp
  } from "@/api/flowDesign/actApp";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import IconSelect from "@/components/IconSelect";
  import axios from 'axios';

  export default {
    name: "Menu",
    components: {
      Treeselect,
      IconSelect
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 菜单表格树数据
        menuList: [],
        // 菜单树选项
        menuOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 显示状态数据字典
        defaultExpandAll:true,
        newApp: false,
        isAdd: true,
        editNowIsApp: false,
        modelOptions: [],
        // 查询参数
        queryParams: {
          systemFlag: ''
        },
        expand: true,
        //导入参数
        upload: {
          fileList: [],
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/actconf/actApp/uploadPic",
          fileName: [],
          id: null
        },
        // 表单参数
        form: {},
        // 表单校验

      };
    },
    created() {
      this.getList();
    },
    methods: {
      getAppCode() {
        if (this.newApp || this.editNowIsApp) {
          genAppCode(this.form).then(res => {
            this.form.appCode = res.data;
          })
        }
      },
      /** 查询菜单列表 */
      getList() {
        this.loading = true;
        listActApps(this.queryParams).then(response => {
          this.menuList = this.handleTree(response.data, "id");
          this.loading = false;
        }).catch(err => {
          this.loading = false;
        })
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.$modal.loading("加载中，请稍后...")
        this.isAdd = true;
        let query = {
          "parentId": null
        };
        if (typeof row === "undefined" || row === '') {
          this.title = "添加应用";
          this.newApp = true;
        } else {
          this.title = "添加分类";
          query.parentId = row.id;
          this.newApp = false;
        }
        console.log("newApp:" + this.newApp);
        console.log("editApp:" + this.editNowIsApp)
        findById(query).then(res => {
          this.form = res.data;
          this.open = true;
          this.$modal.closeLoading();
        });
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.$modal.loading("加载中，请稍后...")
        debugger;
        this.reset();
        if (row.appsTypeName === '应用') {
          this.editNowIsApp = true;
          this.title = '修改应用';
        } else {
          this.editNowIsApp = false;
          this.title = '修改分类';
        }
        let query = {
          "id": row.id
        };
        findById(query).then(res => {
          this.form = res.data;
          this.open = true;
          this.getTreeselect();
          this.$modal.closeLoading();
        });

      },


      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.appName,
          children: node.children
        };
      },
      /** 查询菜单下拉树结构 */
      getTreeselect() {
        const query = {
          modelCode: this.form.modelCode
        };
        listActApps(query).then(response => {
          this.menuOptions = [];
          const menu = {
            id: "0",
            appName: '主类目',
            children: []
          };
          menu.children = this.handleTree(response.data, "id");
          this.menuOptions.push(menu);
        });
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.resetForm("form");
        this.handleQuery();
        this.isAdd = false;
        this.editNowIsApp = false;
        this.newApp = false;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.expand = true;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
      },

      /** 提交按钮 */
      submitForm: function() {
        this.$modal.loading("正在修改数据，请稍后...");
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateApp(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.$modal.closeLoading();
                this.getList();
              });
            } else {
              addNewApp(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.$modal.closeLoading();
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除名称为"' + row.appName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delActApp(row.id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
      },

      handleUpload(row) {
        this.upload.id = row.id;
        this.upload.open = true;
        this.upload.fileList=[];

      },

      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 上传发生变化钩子
      handleFileChange(file, fileList) {
        this.upload.fileList = fileList;
      },
      // 删除之前钩子
      handleFileRemove(file, fileList) {
        this.upload.fileList = fileList;
      },

      // 提交上传文件
      submitFileForm() {
        if (this.upload.fileList.length == 0) {
          this.$modal.msgError("上传文件不能为空");
          return;
        }
        let formData = new FormData();
        this.upload.fileList.forEach(file => {
          formData.append("file", file.raw);
        })
        formData.append("id", this.upload.id);
        let _this = this;
        axios.post(this.upload.url, formData, {
          headers: {
            "Content-Type": "multipart/form-data", //设置请求头
          }
        }).then(res => {
          //上传成功
          if (res.data.code == 200) {
            if (res.data.success) {
              this.$modal.msgSuccess("新增成功！");
              this.upload.open = false;
              this.handleQuery();
            } else {
              this.$confirm(res.data.message, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(function() {
                _this.upload.isOver = 1;
                return _this.submitFileForm();
              })
            }
          } else {
            this.msgError(res.data.msg);
          }
        }).catch(function(error) {
          this.msgError(error);
        })

      },
    }
  };
</script>
